// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html
/**
 * 投注面板
 * 11选5乐选投注面板
 */
cc.Class({
    extends: cc.Component,

    properties: {
        tgAnySelList:[cc.Toggle], //选择玩法按钮列表
        tgRedBall:cc.Prefab,  //球的预制
        betContent:[cc.Node],  //球放置目录
        labWeiDec:[cc.Label],  //位数
        labTopTitle:cc.Label,  //标头
        labDec: cc.RichText,   //说明
        tgSelect:cc.Toggle,   //机选、清空切换按钮    
        labShowAmount: cc.Label,  //显示共注、倍、元、
        manageCenter: cc.Node, 
        scrollview: cc.ScrollView,
        BASEMONEY:[],//单价列表
        rules:[], //规则
        nums:[],  //数值   
        isMiss:false,//是否开启遗漏
        betToggleList:[],//球指针列表
        selRedBall:[],//选择球数字列表
        curPage:0,
        _betManage: null,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        this.initConfig();
        this.initPanel();
    },

    initConfig:function(){
        this.rules = [DEFINE.LOTTERYRULE115.LE_THREE,DEFINE.LOTTERYRULE115.LE_FOUR,DEFINE.LOTTERYRULE115.LE_FIVE]
        //this.names = ["乐三","乐四","乐五"];
        this.nums = ["01","02","03","04","05","06","07","08","09","10","11"]; 
        this.BASEMONEY = [6,10,14];
        
        this.decContents = [
            "<color=#ffffff>至少选3个号码，猜对前3个开奖号即中</c><color=#fcd346>1384元宝</color>",
            "<color=#ffffff>至少选4个号码，猜对任意4个开奖号最高可中</c><color=#fcd346>154元宝</color>",
            "<color=#ffffff>至少选5个号码，猜对全部5个开奖号最高可中</c><color=#fcd346>1080元宝</color>",
        ];
        for(var i=0;i<3;i++)
        {
            var arry = [];
            this.selRedBall.push(arry);
        }
        this._betManage = this.manageCenter.getComponent("bet_115_pop"); 
    },

    //初始化场景信息
    initPanel:function(){   
        for(var i=0;i<this.betContent.length;i++)
        {
            var arry = [];
            for(var j = 0;j<this.nums.length;j++)
            {      
                var ball = cc.instantiate(this.tgRedBall);
                ball.getComponent('bet_sel115_item').init({
                    num: this.nums[j],
                    miss: ""
                });
                var checkEventHandler = new cc.Component.EventHandler();
                checkEventHandler.target = this.node; 
                checkEventHandler.component = "bet_115_leSelect"
                checkEventHandler.handler = "onClickCallback";
                checkEventHandler.customEventData = {num:j+1,type:i};
                ball.getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
                this.betContent[i].addChild(ball);
                arry.push(ball);
            }
            this.betToggleList.push(arry);
            this.labWeiDec[i].node.active = true;
                
        }
        for(var i=0;i<this.tgAnySelList.length;i++)
        {
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "bet_115_leSelect"
            checkEventHandler.handler = "onSelPageCallBack";
            checkEventHandler.customEventData = {
                //name:this.names[i],
                pageID:i+3,
                decContent:this.decContents[i]
            };
            this.tgAnySelList[i].getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        }
        //初始选择第一个小界面
        var temp = this.tgAnySelList[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
        this.onSelPageCallBack(this.tgAnySelList[0],temp);
    },

    onSelPageCallBack:function(toggle, customEventData){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this.scrollview.scrollToTop(0.1);
            //this.labTopTitle.string = customEventData.name;
            this.labDec.string = customEventData.decContent;
            this.curPage = customEventData.pageID;
            for(var i=0;i<3;i++)
            {
                if(this.curPage == 3)
                {
                    this.betContent[i].active = true;
                    this.labWeiDec[0].string = "万位";
                    this.labWeiDec[i].node.active = true;
                }
                else
                {
                    if(i==0)
                    {
                        this.betContent[i].active = true;
                        this.labWeiDec[i].string = "选号";
                        this.labWeiDec[i].node.active = true;
                    }
                    else
                    {
                        this.betContent[i].active = false;
                        this.labWeiDec[i].node.active = false;
                    }
                    
                }
            }
            this.clearCurSel();
            // if(this.isMiss )
            // {
            //     if(this.curPage-3>0)
            //     {
            //         this._betManage.showMiss(this.betToggleList[0],this.lotteryID,this.lotteryID+this.rules[this.curPage-3].toString());
            //     }
            //     else
            //     {
            //         this._betManage.showMissArry(this.betToggleList,this.lotteryID,this.lotteryID+this.rules[this.curPage-3].toString());
            //     }   
            // }
        }  
    },

    onClickCallback:function(toggle, customEventData){
        var num = customEventData.num;
        var type = customEventData.type;
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this.selRedBall[type].push(num);
        }
        else
        {
             Utils.removeByValue(this.selRedBall[type],num);
        }
        this.updateTgSelect();
        this.checkBet();
    },

    updateTgSelect:function(){
        for(var i=0;i<this.selRedBall.length;i++)
        {
            if(this.selRedBall[i].length > 0)
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = true;
                return;
            }
        }
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;
    },


    //清空当前选择
    clearCurSel:function(){
        for(var i=0;i<this.selRedBall.length;i++)
        {
            this.selRedBall[i].length = 0;
        }

        for(var i=0;i<this.betToggleList.length;i++)
        {
            for(var j=0;j<this.betToggleList[i].length;j++)
            {
                this.betToggleList[i][j].getComponent(cc.Toggle).isChecked = false;
            }
        }
      
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;
        this._betManage.setMutipleAmount(1);
        this.checkBet();
    },
 
    checkBet:function(){
        var bet = 0;
        if(this.curPage == 3 )
        {
            bet=1;
            for(var i=0;i<3;i++)
            {
                if(this.selRedBall[i].length == 0)
                {
                    bet = 0;
                    break;
                }
                else
                {
                    bet = this.selRedBall[i].length*bet;
                }
            }
        }
        else
        {
            bet = LotteryUtils.combination(this.selRedBall[0].length,this.curPage);
        }

        var muiple = this._betManage.getMutipleAmount();
        this.setShowAmount(muiple,bet);
    },

    //机选
    randomSelectCallBack:function(){
        this.clearCurSel();
        var temps = [];
        if(this.curPage == 3)
        {
            var tempnum = [];
            for(var i=0;i<this.curPage;i++)
            {
                var randomArray = Utils.getRandomArrayWithArray(this.betToggleList[i], 1);
                var temp = randomArray[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
                
                while(1)
                {
                    if(Utils.findValueByArry(tempnum,temp.num))
                    {
                        randomArray = Utils.getRandomArrayWithArray(this.betToggleList[i], 1);
                        temp = randomArray[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
                    }
                    else
                    {
                        break;
                    }
                }
            
                tempnum.push(temp.num);
                randomArray[0].getComponent(cc.Toggle).isChecked = true; 
                this.onClickCallback(randomArray[0],temp);
            }
        }
        else
        {
            var randomArray = Utils.getRandomArrayWithArray(this.betToggleList[0], this.curPage);      
            for(var i=0;i<randomArray.length;i++)
            {
                randomArray[i].getComponent(cc.Toggle).isChecked = true;
                var temp = randomArray[i].getComponent(cc.Toggle).checkEvents[0].customEventData;
                this.onClickCallback(randomArray[i],temp);
            }
        }  
    },

    //选择清空切换
    onSelectCallBack:function(toggle){
        if(this.isNorm == 0)
        {
            toggle.getComponent(cc.Toggle).isChecked = true;
            this.clearCurSel();
        }
        else
        {
            if(toggle.getComponent(cc.Toggle).isChecked)
            {
                this.randomSelectCallBack();
            }
            else
            {
                this.clearCurSel();
            }
        }
    },

    //显示投注信息
    setShowAmount:function(mut,bet){
        var issue = 1; //this.getIssueNum();
        var money = mut*bet*this.BASEMONEY[this.curPage-3]*issue;
        this._betManage.setMoney(money);
        this._betManage.setBetNum(bet);
        this.labShowAmount.string = "共"+bet+"注"+ mut +"倍"+ issue + "期"+ money+"元宝";
    },

     //投注信息组合
     dataToJson:function(){
        var obj = new Object(); 
        obj.PlayCode = parseInt(this._betManage._lotteryCode + this.rules[this.curPage-3].toString()); 
        var nums = "";
        var num = "";
        if(this.curPage == 3)
        {
            for(var i=0;i<this.selRedBall.length;i++)
            {
                Utils.sortNum(this.selRedBall[i]);
                num = "";
                for(var j=0;j<this.selRedBall[i].length;j++)
                {
                    if(num != "")
                    {
                        num+=",";
                    }
                    var oneNum = this.selRedBall[i][j]>9 ? this.selRedBall[i][j].toString():"0"+this.selRedBall[i][j].toString(); 
                    num += oneNum; 
                }
                nums =  (nums == "") ?num:nums+"|"+num;
            }  
        }
        else
        {
            Utils.sortNum(this.selRedBall[0]);
            num = "";
            for(var j=0;j<this.selRedBall[0].length;j++)
            {
                if(num != "")
                {
                    num+=",";
                }
                var oneNum = this.selRedBall[0][j]>9 ? this.selRedBall[0][j].toString():"0"+this.selRedBall[0][j].toString(); 
                num += oneNum; 
            }
            nums = num;
        }

      var arry = [];
      var numArrays = {
            "Multiple":this._betManage.getMutipleAmount(),
            "Bet":this._betManage.getBetNum(),
            "isNorm":1,
            "Number":nums
        };
        arry.push(numArrays);
        obj.Data = arry;
        var json = JSON.stringify(obj);
        cc.log("提交订单：" + json);
        return json;
    },

    //是否显示-遗漏数组-显示控件列表-彩种id-规则id
    showMiss:function(toggleList,lotteryid,playCode){
        var recv = function(ret){  
            ComponentsUtils.unblock();
            var temparr = [];
            if(ret.Code === 0)
            {
                temparr = ret.Data;
                try {
                    var obj = eval('('+temparr+')');
                    this.setMiss(true,toggleList,obj["o"]);
                } catch (error) {
                  
                }
               
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);  
                this.setMiss(true,toggleList,temparr);
            }
        }.bind(this);
        var data = {
            LotteryCode:lotteryid,
            IsuseName:"1",
            PlayCode:playCode,
            TopCount:100
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETLOTTERYMISS, data, recv.bind(this),"POST");   
        ComponentsUtils.block();
        
    },

    //是否显示-遗漏数组-显示控件列表
    setMiss:function(isMiss,toggleList,missArry){
        if(isMiss)
        {
            if(missArry.length == toggleList.length)
            {
                if(missArry.length > 0)
                {
                    for(var i=0;i<toggleList.length;i++)
                    {
                        toggleList[i].getComponent('bet_sel115_item').setMissNum(missArry[i]);
                    }
                }
                else
                    toggleList[i].getComponent('bet_sel115_item').setMissNum("--");
            }  
        }
        else
        {
            for(var i=0;i<toggleList.length;i++)
            {
                toggleList[i].getComponent('bet_sel115_item').setMissNum("");
            }
        }   
    },

    showMissArry:function(toggleArryList,lotteryid,playCode){
        var recv = function(ret){
            ComponentsUtils.unblock();
            var temparr = [];
            if(ret.Code === 0)
            {
                temparr = ret.Data;
                
                var obj = eval('('+temparr+')');
                this.setMissArry(true,toggleArryList,obj["o"]);
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);  
                this.setMissArry(true,toggleArryList,temparr);
            }
        }.bind(this);
        var data = {
            LotteryCode:lotteryid,
            IsuseName:"1",
            PlayCode:playCode,
            TopCount:100
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETLOTTERYMISS, data, recv.bind(this),"POST");   
        ComponentsUtils.block();
        
    },

    //是否显示-遗漏数组-显示控件列表
    setMissArry:function(isMiss,toggleList,missArry){
        if(isMiss)
        {
            var arrtemp = [];
            if(missArry.length > 5)
            {
                arrtemp.push(missArry);
            }
            else
                arrtemp = missArry;
            if(arrtemp.length > 0)
            {
                for(var i=0;i<arrtemp.length;i++)
                {
                    for(var j=0;j<toggleList[i].length;j++)
                    {
                        toggleList[i][j].getComponent('bet_sel115_item').setMissNum(arrtemp[i][j]);
                    } 
                }
            }
            else
            {
                for(var i=0;i<toggleList.length;i++)
                {
                    for(var j=0;j<toggleList[j].length;j++)
                    {
                        toggleList[i][j].getComponent('bet_sel115_item').setMissNum("--");
                    } 
                }
            }
        }
        else
        {
            for(var i=0;i<toggleList.length;i++)
            {
                for(var j=0;j<toggleList[i].length;j++)
                {
                    toggleList[i][j].getComponent('bet_sel115_item').setMissNum("");
                }
            }
        }   
    },

    // update (dt) {},
});
